package com.bjb.baidu;

import com.baidu.aip.bodyanalysis.AipBodyAnalysis;
import com.bjb.util.Base64ImageUtil;
import org.json.JSONObject;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.HashMap;

/**
 * 百度人体分析
 */
public class BdAipBodyAnalysis {

    public static final String APP_ID = "18268648";
    public static final String API_KEY = "qGDCRcmg14GVjCfcZfQKZt3n";
    public static final String SECRET_KEY = "gK23gw2mtKzRuz5jrYfsGCcv8zTnxGoj";
    public static AipBodyAnalysis client = null;

    static {
        client = new AipBodyAnalysis(APP_ID, API_KEY, SECRET_KEY);
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
    }

    public static BufferedImage resize(BufferedImage img, int newW, int newH) {
        Image tmp = img.getScaledInstance(newW, newH, Image.SCALE_SMOOTH);
        BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = dimg.createGraphics();
        g2d.drawImage(tmp, 0, 0, null);
        g2d.dispose();
        return dimg;
    }

    /**
     * 前景图片
     * @param file
     */
    public static String getForegroundImg(byte[] file, Integer targetWidth) {
        String foregroundData = "";
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("type", "foreground");
        JSONObject res = client.bodySeg(file, options);
        foregroundData = res.getString("foreground");
        BufferedImage bufferedImage = Base64ImageUtil.base64StringToBufferedImage(foregroundData);
        int newWidth = targetWidth;
        float scale = (float) targetWidth / (float) bufferedImage.getWidth();
        int newHeight = Math.round(bufferedImage.getHeight() * scale) ;
        BufferedImage reImg = resize(bufferedImage, newWidth, newHeight);
        return Base64ImageUtil.imageToBase64(reImg, "png");
    }
}
